<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Token;
use app\admin\model\Video;
use app\admin\model\Order;
use app\admin\model\Orderlist;
use app\admin\model\Users;
use app\common\controller\Wxlogin;
class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function _initialize()
    {   

        parent::_initialize();

            $this->video = new Video;
            $this->user  = new Users;
            $this->order  = new Order;
            $this->wxlogin  = new Wxlogin;

    }

    //调试
    public function bug()
    {   
        // return $this->user->getLevel($_GET['id']); 
        session('uid',null);
        $this->success('缓存清除成功,请关闭网页!');
    }
    public function login()
    {   
        $openid = $_GET['openid'];
        $res = Users::get(['openid'=> $_GET['openid']]);
      
        if($res){
            $uid = $res->user_id;
            session('openid',$openid);
            session('uid',$uid);
            $this->redirect('/',301);
        }else{
            //注册用户
           $list = [[
                'openid'=>$openid,
                'user_reg_time'=>time(),
                'user_reg_ip'=>$_SERVER['REMOTE_ADDR'],
                'user_parentid'=>$_GET['daili'],
                'user_name'=>'微信用户'.date('Ymd',time())
           ]];
           $user1 = new Users();
           $userreg = $user1->saveAll($list);
        
           if($userreg){
                session('openid',$openid);
                session('uid',$userreg[0]->user_id);
                // session('uid',$uid);
                $this->redirect('/',301);
                $this->success('登录成功!','/');
                return ['code'=>1,'msg'=>'登录成功!'];
           }else{
            $this->error('登录失败!','/');
                return ['code'=>0,'msg'=>'登录失敗!'];
           }
        }


    }

    /**
     * 
     * jssdk 注入配置 
     * 
     * @param  STRING $_POST['URL']   请求的url
     * 
     * @return json 配置文件
     * 
     */
    public function jsToken()
    {   
        // 拿access_token
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx61d62fce6d4ba436&secret=02a3302b09627facbefd077f17aae50b';
        $res = file_get_contents($url);
        $access_token = (json_decode($res))->access_token;
        return $res;
        // 换取ticket
        $url =  'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
        $res = file_get_contents($url);
        $ticket = json_decode($res)->ticket;
        
        //生成php随机数
        $nonceStr = '';
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';  
        for($i=0;$i<11;$i++)   
        {   
            $nonceStr .= $pattern{mt_rand(0,35)};       
        }   
    


        //ticket
        $jsapi_ticket=$ticket;
        $timestamp=time();

        $url1= $_POST['url'];
        $string = "jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url1}";

        $signPackage = array(
            'appId' => 'wx295c6acc9129a55a',
            'timestamp' => $timestamp,
            'nonceStr' => $nonceStr,
            'signature' => sha1($string),
            'ticket'  => $ticket,
            'access_token'=>$access_token,
            'url'=>$url1,
            'string'=>$string

        );
 
           return $signPackage;

    }

    public function wxpay()
    {    
        $time = time() - 3600;
        //删除超时未支付订单
        Order::where('order_time','<',$time)->where('is_pay',null)->delete();
        

        $_GET["user"] =  empty($_GET["order_id"]) ? $_GET["user"] : $_GET["order_id"];
        //判断是否支付
        $did = $this->order->where(['order_id'=>$_GET["user"],'is_pay'=>1])->find();


        if(isset($_GET['getorder'])){
            return $did;
        }   
        

      

        if($did){
            $this->error('您已经支付过了','/index/index/detail?id='.$_GET['vid']);
        }
        $money = $_GET['price'];

        $token = md5('wx'.$_GET["price"].$_GET["user"]);


        if($token !== $_GET["token"]){
           $this->error('大哥手下留情','/',10);
        }
        

        $h_money = $this->order->where(['order_money'=>$money,'is_pay'=>null])->find();

        //当订单表里存在相同金额时减少,直到没有相同金额为止
        while ($h_money) {
            $money -= 0.01;
            $h_money = $this->order->where(['order_money'=>$money,'is_pay'=>null])->find();
        }
        
        $money = round($money,2);
        // 如果有订单就删除
        if(  $this->order->where(['order_id'=>$_GET['user'],'is_pay'=>null])->find()  ){
            Order::where('order_id',$_GET['user'])->delete();
        }
        Order::create([
            'order_id'=>$_GET['user'],
            'user_id' =>session('uid'),
            'v_id'    =>'vid',
            'order_money'=>$money,
            'order_time' =>time()
        ]);

        

        return view('wxpay',[
            'price'=>$money
        ]);
    }
    public function index()
    {       


        //判断是否代理用户
        $daili = isset($_GET['daili']) ? $_GET['daili'] : 0;
        
        // 微信登录
        if (empty($_GET['code']) &&  empty(session('uid')) ){
            $url = 'http://'.$_SERVER['HTTP_HOST'].'/index/index/login?daili='.$daili;
            $this->redirect('http://api.hbsshop.cn/openid?redirect_uri='.$url,302);


        }
        $this->assign('video',$this->video->order('v_view_num desc video_id')->paginate(10,true) ); 
        $this->assign('pages',     ceil(Video::count() / 10 )); 

  
        return $this->view->fetch();
    }

    public function detail()
    {   
        //判断是否代理用户
        $daili = isset($_GET['daili']) ? $_GET['daili'] : 0;

        // 微信登录
        if (empty($_GET['code']) &&  empty(session('uid')) ){
            $url = 'http://'.$_SERVER['HTTP_HOST'].'/index/index/login?daili='.$daili;
            $this->redirect('http://api.hbsshop.cn/openid?redirect_uri='.$url,302);

        }

        $data = Video::get($_GET['id']);
        //创建订单
        $did = base64_encode(session('openid').'_'.$_GET['id']);
        $money = $data->v_money; 

        

        if(strstr($money,'/')){
            $money = explode('/',$money);
        }else{
            $money = explode('/','4/7');
        }
     
     
        //随机小数
        $f_money1 = rand(1,9);
        $f_money2 = rand(1,9);
        $money    = rand($money[0],$money[1]);
        $money = $money.'.'.$f_money1.$f_money2;
 
        


        //防止傻逼破解的的支付加密token, 支付完成回调 也要校验!!!!!!!!!!
        $token = md5('wx'.$money.$did);

        $ispay = $this->order->where(['order_id'=>$did,'is_pay'=>1])->find();


        $this->video->save(['v_view_num'=>$data->v_view_num + 1],['video_id'=>$_GET['id']]);

        return view('detail',[
            'data'=> $data,
            'money'=> $money,
            'did'=> $did,
            'token'=> $token,
            'ispay'=>$ispay
        ]);
    }   

    //创建订单 然后支付
    public function gopay()
    {   

    }

    // 支付成功回调地址
    public function payok()
    {   

        
        $_GET =  $_POST;
        $order_res = $this->order->where(['order_money'=>$_GET['sum'],'is_pay'=>null])->find();
        if(!$order_res){
            return false;
        }

        $_GET['pay_id'] = $order_res->order_id;
        //拆分订单号
        $id = base64_decode($_GET['pay_id']);
        $id = explode('_',$id);
        $openid = $id[0];
    
        $this->order->save(['is_pay'=>1],['order_id'=>$order_res->order_id]);


        $_GET['price'] =$order_res->order_money;
        //获得代理
        $pid = $this->user->oidinfo($openid,'user_parentid');

        //返利加钱
        $this->user->addMoney($_GET['price'],$pid);
      
        //订单确认
        $res = $this->order->save(['is_pay'=>1],['order_id'=>$_GET['pay_id']]);
   
        //订单写进去
        Orderlist::create([
            'orderlist_name'=>'用户购买',
            'orderlist_money'=>$_GET['price'],
            'orderlist_time'=>time(),
            'orderlist_and' =>'+',
            'uid'           =>$pid

        ]);



    }

    

}
